package network.course5Http.https;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClientPost {
    public  static String sendPost(String uri,String  param,String charset){
        String result=null;
        PrintWriter out=null;
        InputStream in=null;

        try {
           URL url = new URL(uri);
            HttpURLConnection connection= (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            connection.connect();
            out=new PrintWriter(connection.getOutputStream());
            out.print(param);
            out.flush();

            String temp=null;
             in=connection.getInputStream();
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(in,charset));
            StringBuffer stringBuffer=new StringBuffer();

            while((temp=bufferedReader.readLine())!=null){
                   stringBuffer.append(temp);
                   stringBuffer.append("\r\n");
            }
            result=stringBuffer.toString();
           bufferedReader.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
                try {
                    if (in!=null){
                    in.close();
                    }
                    if (out!=null){
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return result;

    }

    public static void main(String[] args) {
        System.out.println(sendPost("http://mis.teach.ustc.edu.cn/kbcx.do","xq=20181&xklb=b&cxfs=0","gbk"));
    }
}
